package org.example.fastproject.web.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Tag;
import org.example.fastproject.core.bean.PageParam;
import org.example.fastproject.core.bean.ViewResult;
import org.example.fastproject.web.sys.model.SysFile;
import org.example.fastproject.web.sys.model.SysUser;
import org.example.fastproject.web.sys.service.SysFileService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 * 文件记录表 前端控制器
 * </p>
 *
 * @author 王海舟
 * @since 2023-02-01 10:56:41
 */
@RestController
@RequestMapping("/sys/sysFile")
@Api(tags = "系统：文件管理")
public class SysFileController {
    @Resource
    private SysFileService fileService;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public ViewResult<Long> upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        if(multipartFile.isEmpty())
            return ViewResult.error("不能上传空文件");
        Long fileId = fileService.upload(multipartFile,false);
        return ViewResult.success("上传成功",fileId);
    }

    @GetMapping("/download")
    @ApiOperation("文件下载")
    public void download(@RequestParam("id") Long fileId) throws IOException {
        fileService.download(fileId);
    }

    @PostMapping("/public")
    @ApiOperation("公开文件上传")
    public ViewResult<Long> uploadPublic(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        if(multipartFile.isEmpty())
            return ViewResult.error("不能上传空文件");
        Long fileId = fileService.upload(multipartFile,true);
        return ViewResult.success("上传成功",fileId);
    }

    @PostMapping("/page")
    @ApiOperation("分页获取文件记录列表")
    @PreAuthorize("hasAuthority('file.page')")
    public ViewResult<Page<SysFile>> page(@RequestBody PageParam param){
        Page<SysFile> page = fileService.page(param);
        return ViewResult.success(page);
    }

    @GetMapping("/{id}")
    @ApiOperation("通过文件id获取文件记录")
    @PreAuthorize("hasAuthority('file.id')")
    public ViewResult<SysFile> getById(@PathVariable Long id){
        SysFile sysFile = fileService.getById(id);
        return ViewResult.success(sysFile);
    }
}
